package com.rfid.emergencywarehouse.reader;

import android.content.Context;

import com.rfid.emergencywarehouse.util.RfidUitl;

import java.util.ArrayList;
import java.util.List;

public class RfidManager {

    private static final String TAG = "RfidManager";
    private static RfidManager mRfidManager;
    private IRfidImpl mIRfid;
    private List<String> mCacheEpcs = new ArrayList<>();
    private RfidListener mRfidListener;

    public static RfidManager getInstance() {
        if(mRfidManager == null) {
            mRfidManager = new RfidManager();
        }
        return mRfidManager;
    }

    public void setRfidListener(RfidListener listener) {
        mRfidListener = listener;
    }

    public List<String> readTags() {
        List<String> result = new ArrayList<>();
        synchronized (mCacheEpcs) {
            result.addAll(mCacheEpcs);
            mCacheEpcs.clear();
        }
        return result;
//        return mIRfid.readTags();
    }


    public String readCellTag(String uid) {
        return RfidUitl.decodeLevelEpc(uid);
    }

    public int writeCellTag(String uid,String a) {
        return 0;
    }

    public RfidManager() {
        mIRfid = new BX6100UhfImpl();
    }

    public boolean setPower(int power) {
        return mIRfid.setPower(power);
    }

    public int getPower() {
        return mIRfid.getPower();
    }

    public void start() {
        mCacheEpcs.clear();
        mIRfid.setRfidListener(new RfidListener() {
            @Override
            public void onRfid(String rfid) {
                synchronized (mCacheEpcs) {
                    mCacheEpcs.add(rfid);
                }
                if(mRfidListener != null) {
                    mRfidListener.onRfid(rfid);
                }
            }
        });
        mIRfid.startScan();
    }

    public void stop() {
        mIRfid.stop();
        mCacheEpcs.clear();
    }

    public void quit() {
        mIRfid.quit();
    }

    public void connect(Context context) {
        mIRfid.connect(context);
    }
}
